package org.abettor.util.struts2;

import java.sql.Clob;
import java.util.Map;

import javax.sql.rowset.serial.SerialClob;

import org.apache.struts2.util.StrutsTypeConverter;

/**
 * 字符串与Clob转化工具
 * @author abettor.org
 *
 */
public class ClobConverter extends StrutsTypeConverter
{
	@SuppressWarnings("rawtypes")
	@Override
	public Object convertFromString(Map context, String[] value, Class toType)
	{
		if(value == null || value.length <= 0)
		{
			return null;
		}

		if(toType == null || ! toType.getName().equals(Clob.class.getName()))
		{
			return null;
		}

		String input = value[0];
		if(input == null)
		{
			return null;
		}

		try
		{
			return new SerialClob(input.toCharArray());
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}

	@SuppressWarnings("rawtypes")
	@Override
	public String convertToString(Map context, Object data)
	{
		if(data == null || ! (data instanceof Clob))
		{
			return null;
		}

		try
		{
			Clob clob = (Clob) data;
			int length = (int) clob.length();
			return clob.getSubString(1, length);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}
}
